/*
* LoginServlet
*
* Version 1.0
*
* Author: phamduong
*/

package chat.process;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.eclipse.jetty.server.session.JDBCSessionManager.Session;

import chat.dao.UserDAO;

public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// redirect to login page
		HttpSession session = request.getSession();
		if (session.getAttribute("currentUser") != null) {
			response.sendRedirect("chat");
		} else {
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();		//get response writer
			out.println("<html>"
					+ "<head>"
					+ "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"
					+ "<title>Dang nhap</title>"
					+ "<link rel='stylesheet' type='text/css' href='css/style.css'>"
					+ "<script type='text/javascript' src='js/login.js'></script>"
					+ "<script type='text/javascript' src='js/util.js'></script>"
					+ "<script type='text/javascript'>"
					+ "</script>"
					+ "</head>"
					+ "<body>"
					+ "<div class='loginblock'>"
					+ "<form action='javascript:login()' method='post' id='loginform'>"
					+ "<table>"
					+ "<tr>"
					+ "<td>Ten dang nhap</td>"
					+ "<td><input type='text' name='username' id='username' /><br></td>"
					+ "</tr>"
					+

					"<tr>"
					+ "<td>Mat khau</td>"
					+ "<td><input type='password' name='password' id='password' /></td>"
					+ "</tr>"
					+

					"<tr>"
					+ "<td columnspan='1'><input type='submit' value='Dang nhap'"
					+ "id='loginaction'></td>" + "</tr>" +

					"</table>" + "</form>" + "</div>" + "</body>" + "</html>");

		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession();
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("name: " + username);
		System.out.println("pass: " + password);
		if (UserDAO.userLogin(username, password) == null) {
			out.print("fail");
		} else {
			/*
			 * RequestDispatcher dispatcher =
			 * request.getRequestDispatcher("/chat");
			 * dispatcher.forward(request, response);
			 */
			out.print("ok");
			session.setAttribute("currentUser", username);
		}
	}
}
